<template>
    <div class="app-container">
        <div class="header">
            <el-button type="primary" size="mini" @click="showSaveStyle">添加</el-button>
            <el-input style="width: 300px; margin-left: 100px;" v-model="styleListForm.memo" size="mini"
                placeholder="输入关键字搜索" @change="styleSearch" @input="checkVal">
                <i slot="suffix" class="el-icon-search"></i>
            </el-input>
        </div>

        <!-- 添加款式弹出框 -->
        <el-dialog title="添加商品款式" :visible.sync="showSaveStyleForm" :close-on-click-modal="false"
            @close="closeSaveStyleForm">
            <el-form ref="saveStyleForm" :model="saveStyleForm" label-width="100px" :rules="saveStyleRules">
                <el-form-item label="款式名称" prop="styleName">
                    <el-input v-model="saveStyleForm.styleName"></el-input>
                </el-form-item>
                <el-form-item label="款式图片" prop="styleImagesId" :rules="checkSelectStyleImagesId">
                    <el-select v-model="selectSaveStyleImagesIdForm.url" placeholder="请选择" popper-class="blueBack"
                        style="width: 100%;" :popper-append-to-body="false" value-key="id"
                        @change="selectSaveStyleImagesId">
                        <el-option v-for="item in imagesList" :key="item.id" :label="item.name" :value="item"
                            style="margin-top: 10px;">
                            <div class="option" style="height: 120px;">
                                <div class="img" style="height: 80px; text-align: center">
                                    <el-image style="width: 120px; height: 120px; margin-right: 5px;" :src="item.url"
                                        fit="fit">
                                        <div slot="error" class="image-slot">
                                            <i class="el-icon-picture-outline"></i>
                                        </div>
                                    </el-image>
                                </div>
                            </div>

                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="当前图片">
                    <el-image style="width: 100px; height: 100px" :src="saveStyleForm.styleImages" fit="fit"
                        v-if="saveStyleForm.styleImages !== ''">
                    </el-image>
                    <el-image v-else style="width: 100px; height: 100px" ></el-image>
                </el-form-item>
                <el-form-item label="所属商品" prop="styleWaresId" :rules="checkSelectStyleWaresId">
                    <el-select v-model="selectSaveStyleWaresIdForm.waresName" placeholder="请选择"
                        popper-class="blueSecoend" :popper-append-to-body="false" value-key="id"
                        @change="selectSaveStyleWaresId">
                        <el-option v-for="item in waresList" :key="item.id" :label="item.name" :value="item">
                            {{ item.waresName }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <div v-for="(item, index) in saveStyleForm.costArr" :key="index">
                    <el-row style="display: flex; align-items: center;">
                        <el-col :span="8">
                            <el-form-item label="价格信息" :prop="'costArr.' + index + '.costMessage'"
                                :rules="[{ required: true, message: '请输入价格信息', trigger: 'change' }]">
                                <el-input v-model="item.costMessage"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="单价" :prop="'costArr.' + index + '.waresPrice'"
                                :rules="[{ required: true, message: '请输入单价', trigger: 'change' }, { type: 'number', message: '必须是数字格式', trigger: 'blur', transform: (value) => Number(value) }]">
                                <el-input v-model="item.waresPrice"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item>
                                <el-button type="primary" icon="el-icon-plus" size="mini"
                                    @click="addSaveItems(saveStyleForm.costArr.length)"
                                    v-if="index + 1 == saveStyleForm.costArr.length"></el-button>
                                <el-button type="danger" icon="el-icon-minus" size="mini"
                                    @click="deleteSaveItems(item, index)" v-if="index !== 0"></el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <el-form-item>
                    <template slot-scope="scope">
                        <el-button type="primary" @click="saveStyleData" :loading="loading">提交</el-button>
                        <el-button @click="closeSaveStyleForm">取消</el-button>
                    </template>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 修改款式弹出框 -->
        <el-dialog title="修改商品款式" :visible.sync="showEditStyleForm" :close-on-click-modal="false"
            @close="closeEditStyleForm">
            <el-form ref="editStyleForm" :model="editStyleForm" label-width="100px" :rules="editStyleRules">
                <el-form-item label="款式名称" prop="styleName">
                    <el-input v-model="editStyleForm.styleName"></el-input>
                </el-form-item>
                <el-form-item label="款式图片" prop="styleImagesId">
                    <el-select v-model="selectEditStyleStyleImagesIdForm.url" placeholder="请选择" popper-class="redBack"
                        :popper-append-to-body="false" value-key="id" @change="selectEditStyleStyleImagesId"
                        style="width: 100%;">
                        <el-option v-for="item in imagesList" :key="item.id" :label="item.name" :value="item"
                            style="margin-top: 10px;">
                            <div class="img" style="height: 120px; text-align: center;">
                                <el-image style="width: 120px; height: 120px;" :src="item.url" fit="fit"></el-image>
                            </div>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="当前图片">
                    <el-image style="width: 100px; height: 100px" :src="editStyleForm.styleImages" fit="fit"></el-image>
                </el-form-item>
                <el-form-item>
                    <template slot-scope="scope">
                        <el-button type="primary" @click="editStyleData" :loading="loading">提交</el-button>
                        <el-button @click="closeEditStyleForm">取消</el-button>
                    </template>
                </el-form-item>
            </el-form>
        </el-dialog>

        <div class="content">
            <el-table :data="styleList" style="width: 100%;" stripe
                :default-sort="{ prop: 'date', order: 'ascending' }">
                <el-table-column label="详情信息">
                    <el-table-column label="款式名称" width="180" prop="styleName">

                        <template slot-scope="scope">
                            <div>{{ scope.row.styleName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="款式图片" width="180" prop="styleImages">

                        <template slot-scope="scope">
                            <el-image style="width: 100px; height: 100px" :src="scope.row.styleImages"
                                fit="contain"></el-image>
                        </template>
                    </el-table-column>
                </el-table-column>

                <el-table-column label="添加">
                    <el-table-column label="添加者">

                        <template slot-scope="scope">
                            <div>{{ scope.row.saveAdmin }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作时间" width="180" sortable prop="date">

                        <template slot-scope="scope">
                            <i class="el-icon-time" v-if="scope.row.saveTime != null"></i>
                            <span style="margin-left: 10px">{{ scope.row.saveTime }}</span>
                        </template>
                    </el-table-column>
                </el-table-column>

                <el-table-column label="删除">
                    <el-table-column label="删除者">

                        <template slot-scope="scope">
                            <div>{{ scope.row.removeAdmin }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="理由">

                        <template slot-scope="scope">
                            <div>{{ scope.row.removeMemo }}</div>
                        </template>
                    </el-table-column>
                </el-table-column>

                <el-table-column label="操作">
                    <el-table-column label="修改">

                        <template slot-scope="scope">
                            <el-button type="primary" circle icon="el-icon-edit"
                                @click="showEditStyle(scope.row.id)"></el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">

                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.isDelete"
                                @change="changeStyleOnAndOffSwitch($event, scope.$index, scope.row)"
                                active-color="#66b1ff" inactive-color="#adadad" active-text="恢复" inactive-text="删除"
                                :active-value="0" :inactive-value="1">
                            </el-switch>
                            <el-switch v-model="scope.row.state"
                                @change="changeStylePutAndPullSwitch($event, scope.$index, scope.row)"
                                active-color="#66b1ff" inactive-color="#adadad" active-text="上架" inactive-text="下架"
                                :active-value="0" :inactive-value="1">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态">

                        <template slot-scope="scope">
                            <el-tag type="success" effect="dark" v-if="scope.row.state == 0">启用</el-tag>
                            <el-tag type="info" effect="dark" v-if="scope.row.state == 1">下架</el-tag>
                            <el-tag type="danger" effect="dark" v-if="scope.row.state == 2">异常</el-tag>
                        </template>
                    </el-table-column>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="styleSizeChange" @current-change="styleCurrentChange"
                :page-size="styleListForm.size" :page-sizes="[10, 20, 30]" layout="total, sizes, prev, pager, next"
                :total="styleTotal" style="margin-top: 20px;">
            </el-pagination>
        </div>
    </div>
</template>

<script>
import utils from '@/utils/checkLogin'
import { getWaresList, getAllStyleList, getAllCostList, getAllImagesListBySelect, getAllWaresListBySelect, getWaresBrandsList, saveStyle, getUpdateStyleInfo, editStyle, offSaleStyle, onSaleStyle, saveCost, getUpdateCostInfo, editCost, offSaleCost, onSaleCost, pullStyle, putStyle } from '../../api/api'
import { jwtDecode } from 'jwt-decode'
import { Message } from 'element-ui'
export default {
    data() {
        return {
            loading: false,
            waresList: [],
            imagesList: [],
            showSaveStyleForm: false,
            styleList: [],
            styleTotal: 0,
            styleListForm: {
                memo: '',
                page: 1,
                size: 10
            },
            showSaveStyleForm: false,
            waresListForm: {
                page: 1,
                size: 10,
                memo: ''
            },
            imagesListForm: {
                page: 1,
                size: 10,
                meno: ''
            },
            saveStyleForm: {
                styleName: '',
                styleImagesId: null,
                waresId: null,
                styleImages: '',
                costArr: [
                    {
                        costMessage: '',
                        waresPrice: ''
                    }
                ]
            },
            checkSelectStyleImagesId: [{
                required: true,
                message: '请选择款式图片',
                validator: this.styleImagesIdValidator
            }],
            checkSelectStyleWaresId: [{
                required: true,
                message: '请选择所属商品',
                validator: this.styleWaresIdValidator
            }],
            saveStyleRules: {
                styleName: [
                    { required: true, message: '请输入款式名称', trigger: 'change' }
                ],
                styleImagesId: [
                    { required: true, message: '请选择款式图片', trigger: ['blur', 'change'] }
                ],
                styleWaresId: [
                    { required: true, message: '请选择款式图片', trigger: ['blur', 'change'] }
                ],
                waresPrice: [
                    { required: true, message: '请输入单价', trigger: 'change' },
                    { type: 'number', message: '输入的值必须为数字', trigger: 'blur', transform: (value) => Number(value) },
                ]
            },
            showEditStyleForm: false,
            editStyleForm: {
                styleId: null,
                styleName: '',
                styleImagesId: null
            },
            editStyleRules: {
                styleName: [
                    { required: true, message: '请输入款式名称', trigger: 'change' }
                ]
            },
            selectSaveStyleImagesIdForm: {
                url: ''
            },
            selectSaveStyleWaresIdForm: {
                waresName: ''
            },
            selectEditStyleStyleImagesIdForm: {
                styleName: '',
                url: ''
            },
        }
    },
    methods: {
        styleImagesIdValidator(rule, value, callback) {
            if (this.selectSaveStyleImagesIdForm.url === '') {
                callback(new Error('请选择款式图片'))
            } else {
                callback()
            }
        },
        // styleEditImagesIdValidator(rule, value, callback) {
        //     if (this.selectEditStyleStyleImagesIdForm.url === '') {
        //         callback(new Error('请选择款式图片'))
        //     } else {
        //         callback()
        //     }
        // },
        styleWaresIdValidator(rule, value, callback) {
            if (this.selectSaveStyleWaresIdForm.waresName === '') {
                callback(new Error('请选择所属商品'))
            } else {
                callback()
            }
        },
        getImagesListData() {
            getAllImagesListBySelect().then((res) => {
                if (res.code == 200) {
                    console.log('全部素材列表', res)
                    this.imagesList = res.data
                }
            })
        },
        getWaresListData() {
            getAllWaresListBySelect().then((res) => {
                if (res.code == 200) {
                    this.waresList = res.data
                    console.log('全部商品列表', res);
                }
            })
        },
        getAllStyleListData() {
            getAllStyleList(this.styleListForm).then((res) => {
                if (res.code == 200) {
                    console.log('全部商品款式', res)
                    this.styleList = res.data
                    this.styleTotal = res.total
                }
            })
        },
        styleSizeChange(e) {
            this.styleListForm.size = e
            this.getAllStyleListData()
        },
        styleCurrentChange(e) {
            this.styleListForm.page = e
            this.getAllStyleListData()
        },
        // 搜索
        styleSearch() {
            this.getAllStyleListData()
        },
        // 如果搜索框的值为空，刷新一下款式列表
        checkVal() {
            if (this.styleListForm.memo == '') {
                this.getAllStyleListData()
            }
        },
        selectSaveStyleImagesId(e) {
            this.selectSaveStyleImagesIdForm.url = e.url
            this.saveStyleForm.styleImagesId = e.id
            this.saveStyleForm.styleImages = e.url
        },
        selectSaveStyleWaresId(e) {
            console.log(e)
            this.selectSaveStyleWaresIdForm.waresName = e.waresName
            this.saveStyleForm.waresId = e.id
        },
        saveStyleData() {
            this.$refs.saveStyleForm.validate(valid => {
                if (!valid) {
                    Message({
                        message: '请检查表单',
                        type: 'warning',
                        duration: 2000,
                    })
                    return false
                } else {
                    console.log(JSON.stringify(this.saveStyleForm))
                    saveStyle(this.saveStyleForm).then((res) => {
                        if (res.code == 200) {
                            console.log('添加款式', res)
                            Message({
                                message: '添加成功',
                                type: 'success',
                                duration: 2000
                            })
                            this.loading = true
                            this.getAllStyleListData()
                            setTimeout(() => {
                                this.showSaveStyleForm = false
                                this.loading = false
                                // this.showStyleForm = false
                                // this.restSaveWaresForm()
                                this.$nextTick(() => {
                                    this.$refs.saveStyleForm.resetFields()
                                    this.$set(this.selectSaveStyleImagesIdForm, 'url', '')
                                    this.$set(this.selectSaveStyleWaresIdForm, 'waresName', '')

                                })
                            }, 1500)
                        } else {
                            Message({
                                message: '添加失败',
                                type: 'warning',
                                duration: 2000
                            })
                        }
                    })
                }
            })
        },
        showSaveStyle() {
            this.showSaveStyleForm = true
            this.getWaresListData()
            this.getImagesListData()
        },
        closeSaveStyleForm() {
            this.showSaveStyleForm = false
            this.$nextTick(() => {
                this.$refs.saveStyleForm.resetFields()
                this.$set(this.selectSaveStyleImagesIdForm, 'url', '')
                this.$set(this.selectSaveStyleWaresIdForm, 'waresName', '')
                this.$set(this.saveStyleForm, 'styleImages', '')
            })
        },
        addSaveItems() {
            this.saveStyleForm.costArr.push({
                costMessage: '',
                waresPrice: ''
            })
        },
        deleteSaveItems(item, index) {
            this.saveStyleForm.costArr.splice(index, 1)
        },
        closeEditStyleForm() {
            this.showEditStyleForm = false
        },
        showEditStyle(styleId) {
            this.getImagesListData()
            this.showEditStyleForm = true
            this.editStyleForm.styleId = styleId
            let data = {
                styleId
            }
            getUpdateStyleInfo(data).then((res) => {
                if (res.code == 200) {
                    console.log('修改款式（数据回显）', res)
                    this.editStyleForm.styleName = res.data.styleName
                    this.selectEditStyleStyleImagesIdForm.url = res.data.styleImages
                    this.editStyleForm.styleImages = res.data.styleImages
                }
            })

        },
        selectEditStyleStyleImagesId(e) {
            this.selectEditStyleStyleImagesIdForm.url = e.url
            this.editStyleForm.styleImagesId = e.id
        },

        editStyleData() {
            console.log(JSON.stringify(this.editStyleForm))
            editStyle(this.editStyleForm).then((res) => {
                if (res.code == 200) {
                    Message({
                        message: '修改成功',
                        type: 'success',
                        duration: 3000
                    })
                    console.log('修改款式', res)
                    this.loading = true
                    setTimeout(() => {
                        this.showEditStyleForm = false
                        this.loading = false
                        this.getAllStyleListData()
                        // this.restSaveWaresForm()
                        this.$nextTick(() => {
                            this.$refs.editStyleForm.resetFields()
                        })
                    }, 2000)

                } else {
                    Message(({
                        message: '修改失败',
                        type: 'success',
                        duration: 2000
                    }))
                }
            })
        },

        closeSaveCostForm() {
            console.log('1');
            this.showSaveCostForm = false
        },
        // 保存提交价格
        saveCostData() {
            this.saveCostForm.waresId = this.costForm.waresId
            console.log(JSON.stringify(this.saveCostForm))
            this.$refs.saveCostForm.validate(valid => {
                if (!valid) {
                    Message({
                        message: '请检查表单！',
                        type: 'warning',
                        duration: 2000
                    })
                    return false
                } else {
                    saveCost(this.saveCostForm).then((res) => {
                        if (res.code == 200) {
                            console.log('添加价格', res)
                            Message({
                                message: '添加成功',
                                type: 'success',
                                duration: 2000
                            })
                            this.getAllStyleListData()
                            setTimeout(() => {
                                this.showSaveCostForm = false
                                this.showCostListForm = false
                                this.restSaveWaresForm()
                                this.$nextTick(() => {
                                    this.$refs.saveCostForm.resetFields()
                                })
                            }, 1500)
                        } else {
                            Message({
                                message: '添加成失败',
                                type: 'warning',
                                duration: 2000
                            })
                        }
                    })
                }
            })
        },


        changeStyleOnAndOffSwitch($event, index, row) {
            console.log('$event', $event);
            // 删除
            if ($event) {
                console.log('已删除');
                let removeStyleForm = {
                    styleId: row.id,
                    removeRelated: true
                }
                this.$confirm('是否删除该款式?', '删除提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$prompt('请输入删除理由', '删除提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    }).then(({ value }) => {
                        removeStyleForm.removeMemo = value
                        console.log(JSON.stringify(removeStyleForm));
                        offSaleStyle(removeStyleForm).then((res) => {
                            if (res.code == 200) {
                                console.log('删除成功', res);
                                this.$message({
                                    type: 'success',
                                    message: '删除成功',
                                    duration: 2000
                                })
                                setTimeout(() => {
                                    this.showCostListForm = false
                                    this.getAllStyleListData()
                                }, 1000)
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: '删除失败',
                                    duration: 2000
                                })
                            }
                        })

                    }).catch(() => {
                        this.styleList[index].isDelete = $event
                        this.getAllStyleListData()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                    this.styleList[index].isDelete = $event
                    this.getAllStyleListData()
                })
            } else {
                // 恢复
                console.log('已恢复');
                let noRemoveStyleForm = {
                    styleId: row.id,
                }
                console.log(JSON.stringify(noRemoveStyleForm));
                onSaleStyle(noRemoveStyleForm).then((res) => {
                    if (res.code == 200) {
                        console.log('恢复成功', res);
                        this.$message({
                            type: 'success',
                            message: '恢复成功',
                            duration: 2000
                        })
                        setTimeout(() => {
                            this.getAllStyleListData()
                        }, 1000)
                    } else {
                        this.$message({
                            type: 'error',
                            message: '恢复失败',
                            duration: 2000
                        })
                    }
                })
            }
        },

        changeStylePutAndPullSwitch($event, index, row) {
            console.log('$event', $event);
            // 下架
            if ($event) {
                console.log('已下架');
                let pullStyleForm = {
                    styleId: row.id,
                }
                this.$confirm('是否下架该款式?', '下架提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$prompt('请输入下架理由', '下架提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    }).then(({ value }) => {
                        pullStyleForm.memo = value
                        console.log(JSON.stringify(pullStyleForm));
                        pullStyle(pullStyleForm).then((res) => {
                            if (res.code == 200) {
                                console.log('下架成功', res);
                                this.$message({
                                    type: 'success',
                                    message: '下架成功',
                                    duration: 2000
                                })
                                setTimeout(() => {
                                    this.showCostListForm = false
                                    this.getAllStyleListData()
                                }, 1000)
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: '下架失败',
                                    duration: 2000
                                })
                            }
                        })

                    }).catch(() => {
                        this.styleList[index].state = $event
                        this.getAllStyleListData()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消下架'
                    })
                    this.styleList[index].state = $event
                    this.getAllStyleListData()
                })
            } else {
                // 上架
                console.log('已上架');
                let noPullStyleForm = {
                    styleId: row.id,
                }
                console.log(JSON.stringify(noPullStyleForm));
                putStyle(noPullStyleForm).then((res) => {
                    if (res.code == 200) {
                        console.log('上架成功', res);
                        this.$message({
                            type: 'success',
                            message: '上架成功',
                            duration: 2000
                        })
                        setTimeout(() => {
                            this.getAllStyleListData()
                        }, 1000)
                    } else {
                        this.$message({
                            type: 'error',
                            message: '上架失败',
                            duration: 2000
                        })
                    }
                })
            }
        }

    },
    created() {
        utils.checkLogin()
        this.getAllStyleListData()
    }
}
</script>

<style lang="less" scoped>
.app-container {
    padding: 40px;

    .header {
        align-items: center;
        display: flex;
        margin-bottom: 20px;

        .el-icon-search {
            cursor: pointer;
            margin-right: 4px;
            margin-top: 8px;
        }

    }

    .blueBack {
        .el-select-dropdown__item {
            height: 120px;
        }
    }

    .blueSecoend {
        .el-select-dropdown__item {
            height: 36px;
        }
    }

    .redBack {
        .el-select-dropdown__item {
            height: 100%;
        }
    }

    .redSecoend {
        .el-select-dropdown__item {
            height: 36px;
        }
    }


    .content {
        text-align: center;

        .el-select-dropdown__item {
            height: auto;
        }
    }
}
</style>